<template>
  <div class="setting-container">
    <div class="setting-content">
      <h2 class="page-title">个人设置</h2>
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        layout="vertical"
      >
        <div class="avatar-section">
          <a-upload
            v-model="fileList"
            name="image"
            list-type="picture-circle"
            class="avatar-uploader"
            :show-upload-list="false"
            :before-upload="beforeImageUpload"
            :customRequest="handleAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="avatar-img"/>
            <div v-else class="upload-placeholder">
              <plus-outlined />
              <div style="margin-top: 8px">上传头像</div>
            </div>
          </a-upload>
        </div>

        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" />
        </a-form-item>

        <a-form-item label="密码" name="password">
          <a-input-password v-model:value="formState.password" />
        </a-form-item>

        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" />
        </a-form-item>

        <a-form-item label="联系方式" name="contact">
          <a-input v-model:value="formState.contact" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSubmit" block>保存修改</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { beforeImageUpload } from '@/api/utils';
import { userApi } from '@/api';
import http from '@/api/http';
import { useRouter } from 'vue-router';

const formRef = ref();
const imageUrl = ref('');
const fileList = ref([]);
const router = useRouter();

const formState = reactive({
  username: '',
  password: '',
  email: '',
  contact: '',
  userAvatar: ''
});

const rules = {
  username: [{ required: true, message: '请输入用户名' }],
  password: [{ min: 6, message: '密码长度不能小于6位' }],
  email: [{ type: 'email', message: '请输入正确的邮箱格式' }]
};

onMounted(async () => {
  try {
    const res = await userApi.getUserInfo();
    if (res.code === 0 && res.data) {
      // 直接更新整个表单状态
      Object.assign(formState, {
        username: res.data.username || '',
        email: res.data.email || '',
        contact: res.data.contact || '',
        password: '',  // 密码不回显
        userAvatar: res.data.userAvatar || ''
      });
      // 更新头像
      imageUrl.value = res.data.userAvatar || '';
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
});

const handleAvatarUpload = async ({ file, onSuccess, onError }) => {
  try {
    const formData = new FormData();
    formData.append('image', file);
    const res = await http.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    if (res.code === 0) {
      imageUrl.value = res.data;
      formState.userAvatar = res.data;
      message.success('头像上传成功');
      onSuccess();
    } else {
      onError();
      message.error('头像上传失败');
    }
  } catch (error) {
    onError();
    message.error('头像上传失败');
  }
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    const res = await userApi.updateUser(formState);
    if (res.code === 0) {
      message.success('保存成功');
      // 更新本地存储的用户信息
      const userInfo = {
        username: formState.username,
        userAvatar: formState.userAvatar
      };
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
      // 更新全局状态
      // window.location.reload(); // 刷新页面以更新头像
      router.push('/');
    }
  } catch (error) {
    message.error('保存失败：' + error.message);
  }
};
</script>

<style scoped>
.setting-container {
  width: 100%;
  min-height: 100vh;
  padding: 24px;
  background: linear-gradient(135deg, #0257a7 0%, #69c0ff 100%);
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.setting-content {
  width: 100%;
  max-width: 800px;
  padding: 32px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.page-title {
  text-align: center;
  color: #1890ff;
  font-size: 24px;
  margin-bottom: 32px;
}

.avatar-section {
  text-align: center;
  margin-bottom: 32px;
  border: 1px dashed #1890ff;
  padding: 15px;
  border-radius: 10px;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #1890ff;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

.ant-form-item :deep(.ant-form-item-label) {
  text-align: left;
}

:deep(.ant-input),
:deep(.ant-input-password) {
  height: 40px;
  line-height: 40px;
}

:deep(.ant-input-password .ant-input) {
  height: 38px;
}

:deep(.ant-input-affix-wrapper) {
  padding: 0 11px;
}

.ant-btn :deep(.ant-btn) {
  height: 40px;
  font-size: 16px;
}
</style> 